<?php
namespace app\admin\controller;

use app\admin\model\MsgModel;
use app\admin\model\UserModel;
class Socketmsg extends Base{
	public function index() {
		$user_id = input("get.user_id");
		return $this->fetch();
	}

	/**
	 * [消息展示]
	 */
	public function show() {

		$msg_id = input('get.msg_id');
		$msgModel = new MsgModel();
		$msgInfo = $msgModel->where('id',$msg_id)->find()->toArray();
		$read_ids = explode(",",$msgInfo['read_ids']);
		$read_ids[] = "|".session("id")."|";
		$read_ids = array_merge(array_filter(array_unique($read_ids)));
		$read_ids = implode(",",$read_ids);
		$msgModel->where('id',$msg_id)->update(['read_ids' => $read_ids]);
		$this->assign([
			"MSG" => $msgInfo,
			'ConversationId' => $msg_id
		]);
		if(isMobile()){
			return $this->fetch("mobile_show");
		}
		return $this->fetch();
	}

	/**
	 * [消息会话]
	 */
	public function Conversation() {
		$param = input('post.');
		// 数据整理
		$send_id = session('id');
		$userModel = new UserModel();
		$userInfo = $userModel->where("id",$send_id)
			->field('id,head,real_name')->find()->toArray();
		$msg = $param['msg'];
		$savedMsg = socketMsg_encode($send_id,$userInfo,$msg);
		$msg_id = $param['msg_id'];
		$msgModel = new MsgModel();
		$msgInfo = $msgModel->where('id',$msg_id)->find();
		$uid_str = $msgInfo['user_ids'];
		$uid_arr = explode(",",$uid_str);
		$user_ids = [];
		foreach($uid_arr as &$v){
			$i = explode("|",$v)[1];
			if($i != $send_id){
				$user_ids[] = $i;
			}
			$v = $msg_id."_".$i;
		}
		$uid_str = implode(",",$uid_arr);
		$user_ids = implode(",",$user_ids);
		// 写入数据库
		$return['save_db'] = $msgModel->saveConversation($msg_id,$send_id,$savedMsg,$msg);
		// 推送
		$userInfo['msg_name'] = $msgInfo['msg_name'];
		$return['to_msgbox'] = send_socket_msg($uid_str,$msg,$userInfo);
		$userInfo['chat_room_id'] = $msgInfo['id'];
		$userInfo['chat_room_name'] = $msgInfo['msg_name'];
		$return['to_desktop'] = send_socket_msg($user_ids,$msg,$userInfo);
		return $return;
	}

	/**
	 * [系统推送消息]
	 */
	public function sysPush() {
		$msg = input("post.msg");
		$msgModel = new MsgModel();
		$userModel = new UserModel();
		$ids = $userModel->column('id');
		$ids = implode(",",$ids);
		return $this->socketSendMsg($ids,$msg);
	}

	/**
	 * [群聊管理]
	 */
	public function groupChat() {
		$param = input("post.");
		$limit = $param['pageSize'];
		$offset = ($param['pageNumber'] - 1) * $limit;
		$msgModel = new MsgModel();
		$userModel = new UserModel();
		$return['rows'] = $msgModel->where('create_uid',session('id'))
			->limit($offset,$limit)->order("id desc")->select()->toArray();
		foreach($return['rows'] as &$v){
			$user_ids = $v['user_ids'];
			$user_ids = explode(",",$user_ids);
			foreach($user_ids as &$va){
				$va = explode("|",$va)[1];
				$v['users'][$va]['id'] = $va;
				$v['users'][$va]['real_name'] = $userModel->where('id',$va)->value("real_name");
			}
		}
		$return['total'] = $msgModel->where('create_uid',session('id'))->count();
		return ['code'=>1,'msg'=>'加载成功','data'=>$return];
	}

	/**
	 * [新建聊天室]
	 */
	public function addChat() {
		$param = input("post.");
		$msgModel = new MsgModel();
		$data = [
			'msg_name' => $param['msg_name'],
			'user_ids' => "|".session('id')."|",
			'create_uid' => session('id'),
			'msg_type' => 0,
		];
		$msgModel::startTrans();
		try {
			$msgModel->insert($data);
			$msgModel::commit();
			return ['code'=>1,'msg'=>'新建成功'];
		} catch (\Exception $e) {
			$msgModel::rollback();
			return ['code'=>0,'msg'=>'新建失败：'.$e->getMessage()];
		}
	}

	/**
	 * [编辑聊天室]
	 */
	public function editChat() {
		$param = input("post.");
		$msgModel = new MsgModel();
		$data = [
			'msg_name' => $param['msg_name'],
			'create_uid' => session('id'),
			'msg_type' => 0,
		];
		$msgModel::startTrans();
		try {
			$msgModel->where(['id'=>$param['id']])->update($data);
			$msgModel::commit();
			return ['code'=>1,'msg'=>'编辑成功'];
		} catch (\Exception $e) {
			$msgModel::rollback();
			return ['code'=>0,'msg'=>'编辑失败：'.$e->getMessage()];
		}
	}

	/**
	 * [删除聊天室]
	 */
	public function delChat() {
		$param = input("post.");
		$msgModel = new MsgModel();
		$msgModel::startTrans();
		try {
			$msgModel->where(['id'=>$param['id']])->delete();
			$msgModel::commit();
			return ['code'=>1,'msg'=>'删除成功'];
		} catch (\Exception $e) {
			$msgModel::rollback();
			return ['code'=>0,'msg'=>'删除失败：'.$e->getMessage()];
		}
	}

	/**
	 * [踢出成员]
	 */
	public function delMember() {
		$param = input("post.");
		$msgModel = new MsgModel();
		$msgModel::startTrans();
		try {
			$old_val = $msgModel->where("id",$param['msg_id'])->value("user_ids");
			$user_ids = explode(",",$old_val);
			foreach($user_ids as &$v){
				if($v == "|".$param['user_id']."|"){
					$v = "";
				}
			}
			$user_ids = implode(",",array_merge(array_filter(array_unique($user_ids))));
			$msgModel->where(['id'=>$param['msg_id']])->update([
				'user_ids' => $user_ids
			]);
			$msgModel::commit();
			return ['code'=>1,'msg'=>'踢出成功'];
		} catch (\Exception $e) {
			$msgModel::rollback();
			return ['code'=>0,'msg'=>'踢出失败：'.$e->getMessage()];
		}
	}

	/**
	 * [添加成员]
	 */
	public function addMember() {
		$param = input("post.");
		$msgModel = new MsgModel();
		$msgModel::startTrans();
		try {
			$old_val = $msgModel->where("id",$param['msg_id'])->value("user_ids");
			$arr = [];
			foreach($param['user_ids'] as $v){
				$arr[] = "|".$v."|";
			}
			$str = implode(",",$arr);
			$new_val = $old_val.",".$str;
			$new_val = explode(",",$new_val);
			$new_val = implode(",",array_merge(array_filter(array_unique($new_val))));
			$msgModel->where(['id'=>$param['msg_id']])->update([
				'user_ids' => $new_val
			]);
			$msgModel::commit();
			return ['code'=>1,'msg'=>'添加成功'];
		} catch (\Exception $e) {
			$msgModel::rollback();
			return ['code'=>0,'msg'=>'添加失败：'.$e->getMessage()];
		}
	}

	/**
	 * [清除聊天记录]
	 */
	public function clearRecord() {
		$param = input("post.");
		$msgModel = new MsgModel();
		$msgModel::startTrans();
		try {
			$msg = "<h5 style='text-align:center'>记录清除时间:".date('Y-m-d H:i')."</h5>";
			if(isset($param['msg_type'])){
				$msgModel->where('msg_type',$param['msg_type'])->update(['msg' => $msg]);
			}else{
				$msgModel->where('id',$param['id'])->update(['msg' => $msg]);
			}
			$msgModel::commit();
			return ['code'=>1,'msg'=>'聊天记录清除成功'];
		} catch (\Exception $e) {
			$msgModel::rollback();
			return ['code'=>0,'msg'=>'聊天记录清除失败：'.$e->getMessage()];
		}
	}
}
